package com.zhijian.warehouse.manage.tcp;

import com.zhijian.warehouse.manage.service.TcpService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author HCG
 * @version 1.0
 * @date 2023-12-04
 */
@Component
public class TcpHandler extends ChannelInboundHandlerAdapter {

    private static TcpHandler tcpHandler;

    @Autowired
    private TcpService tcpService;

    public TcpService getTcpService() {
        return tcpService;
    }

    public static ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();

    public static ConcurrentHashMap<String, Object> map2 = new ConcurrentHashMap<>();

    public ConcurrentHashMap<String, Object> getMap() {
        return map;
    }

    public ConcurrentHashMap<String, Object> getMap2() {
        return map2;
    }

    @PostConstruct
    public void init() {
        tcpHandler = this;
    }

    /*
     * channelAction
     *
     * channel 通道 action 活跃的
     *
     * 当客户端主动链接服务端的链接后，这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
     *
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        tcpHandler.tcpService.initTcpProperty(tcpHandler, ctx);

        if (ctx.channel().remoteAddress() != null) {
            map.put(ctx.channel().remoteAddress().toString(), ctx);
        }
        System.out.println(ctx.channel().remoteAddress().toString() + " 通道已激活！");
    }

    /*
     * channelInactive
     *
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     *
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress().toString() + " 通道不活跃！");
        // 关闭流
        ctx.close();
    }

    /**
     * 功能：读取客户端发送过来的信息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
//            MyPackage msg1 = (MyPackage) msg;
//            System.out.println(msg1);
            ByteBuf buf = (ByteBuf) msg;
            //创建目标大小的数组
            byte[] barray = new byte[buf.readableBytes()];
            //把数据从bytebuf转移到byte[]
            buf.getBytes(0, barray);
            String heart = new String(barray, "UTF-8");
            heart = heart.trim();

            System.out.println("收到的TCP消息 tcpStr =" + heart);

            if (heart.startsWith("heart")) {
                //DTU的ID
                String thingId = String.valueOf(heart).substring(6);

                map2.put(thingId, ctx);
                tcpHandler.tcpService.deviceOnline(thingId);
                tcpHandler.tcpService.changeConditionStatus(ctx, heart);
            } else {
                tcpHandler.tcpService.tcpUpMsgHandle(ctx, heart);
            }


            buf.release();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    public void downMsgSend(String clientIP, String message) {
        System.out.println("TCP下行发送数据 = " + message);
        System.out.println("clientIP===" + clientIP);
        System.out.println(map.get(clientIP));
        if (map.get(clientIP) != null) {
            ChannelHandlerContext ctx = (ChannelHandlerContext) map.get(clientIP);
            writeMessage(ctx, message);
        }
    }

    /**
     * 功能：读取完毕客户端发送过来的数据之后的操作
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    }

    /*
      obj：byte数组
    */

    public void writeMessage(ChannelHandlerContext ctx, String receiveStr) {

        try {
            byte[] bytes = Hex.decodeHex(receiveStr.toCharArray());
            ByteBuf bufff = Unpooled.wrappedBuffer(bytes);
            ctx.writeAndFlush(bufff);
            System.out.println("发送完毕");
        } catch (Exception e) {

        }
    }


    /**
     * 功能：服务端发生异常的操作
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息：\r\n" + cause.getMessage());
    }
}
